package cn.xueden.config;

import com.alibaba.fastjson2.support.spring6.data.redis.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**功能描述：Redis配置
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.config
 * @version:1.0
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        // 创建RedisTemplate对象实例
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        // 配置Redis连接工厂
        redisTemplate.setConnectionFactory(factory);

        // 配置序列化方式
        // key-value序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        // 初始化RedisTemplate对象
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 配置Redis缓存管理器
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory factory){
        // 配置默认缓存参数
        RedisCacheConfiguration  config = RedisCacheConfiguration.defaultCacheConfig()
                // 使用StringRedisSerializer序列化缓存键
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 使用GenericFastJsonRedisSerializer序列化缓存值
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()))
                // 缓存数据保存1小时
                .entryTtl(Duration.ofHours(1L));

        // 创建RedisCacheManager对象实例
        return RedisCacheManager.builder(factory)
                // 设置默认缓存参数
                .cacheDefaults(config)
                .build();

    }
}
